package com.jwsoft.manager.core.integration.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.assistant.common.vo.BaseVO;
import com.bifang.assistant.common.vo.SessionInfo;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.data.core.util.PagerUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.vo.personInformationAuth.*;
import com.jwsoft.manager.core.dao.model.EduStudentEnroll;
import com.jwsoft.manager.core.dao.model.EduStudentEnrollPre;
import com.jwsoft.manager.core.dao.service.EduStudentEnrollPreService;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import cn.hutool.core.convert.Convert;

import java.awt.geom.QuadCurve2D;
import java.util.ArrayList;
import java.util.List;
import com.bifang.engine.assistant.core.exception.AppException;
import org.springframework.util.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.jwsoft.manager.core.integration.PersonInformationAuthIntegration;
import com.jwsoft.manager.core.dao.service.PersonInformationAuthService;
import com.jwsoft.manager.core.dao.model.PersonInformationAuth;
/**
 * 个人信息授权业务实现类
 *
 * @author chenzh
 * @since 2024-03-16
 */
@ApiService(funcCode = "personInformationAuth", title = "个人信息授权")
public class PersonInformationAuthIntegrationImpl implements PersonInformationAuthIntegration {

    @Autowired
    public PersonInformationAuthService personInformationAuthService;
    @Autowired
    private EduHelper eduHelper;
    @Autowired
    private EduStudentEnrollPreService eduStudentEnrollPreService;

    @Override
    @OpApi(funcCode = "personInformationAuth0001", title = "个人信息授权分页查询", funcType = FuncTypeEnum.query)
    public PageInfo<PersonInformationAuthVO> getList(PersonInformationAuthQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(20);
        }
        if (vo.getPersonInformationYear()==null){
            vo.setPersonInformationYear(eduHelper.thisYear());
        }
        QueryWrapper<PersonInformationAuth> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(PersonInformationAuth::getPersonInformationYear,vo.getPersonInformationYear())
                .eq(StringUtils.isNotBlank(vo.getPersonInformationType()),PersonInformationAuth::getPersonInformationType,vo.getPersonInformationType())
                .eq(StringUtils.isNotBlank(vo.getPersonInformationStatus()),PersonInformationAuth::getPersonInformationStatus,vo.getPersonInformationStatus())
                .eq(StringUtils.isNotBlank(vo.getIdcard()),PersonInformationAuth::getIdcard,vo.getIdcard())
                .eq(StringUtils.isNotBlank(vo.getUserId()),PersonInformationAuth::getUserId,vo.getUserId())
                .eq(vo.getPersonId()!=null,PersonInformationAuth::getPersonId,vo.getPersonId());
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());

        List<PersonInformationAuth> list = personInformationAuthService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<PersonInformationAuth> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<PersonInformationAuthVO> resultList = Convert.toList(PersonInformationAuthVO.class, pageInfo.getList());
        // 转义数据字典值
        // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "personInformationAuth0007", title = "根据身份证查询授权信息", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public List<PersonInformationAuthVO> getByIdcard(PersonInformationAuthQueryVO vo) {
        if (StringUtils.isBlank(vo.getIdcard())){
            SessionInfo sessionInfo=SessionUtil.getSessionInfo();
            if (sessionInfo!=null){
                vo.setIdcard(sessionInfo.getIdcard());
            }
        }
        if (StringUtils.isBlank(vo.getIdcard())){
            throw new AppException("请先传入身份证");
        }
        return personInformationAuthService.getByIdcard(vo.getIdcard());
    }

    @Override
    @OpApi(funcCode = "personInformationAuth0009", title = "校验登录人员是否授权", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public Boolean checkAuth(PersonInformationAuthCheckVO baseVO) {
        String idcard="";
        SessionInfo sessionInfo=SessionUtil.getSessionInfo();
        if (sessionInfo!=null){
            idcard=sessionInfo.getIdcard();
        }

        if (StringUtils.isBlank(idcard)){
            throw new AppException("用户信息身份证信息未空");
        }
        boolean checkFlag=true;
        if(baseVO.getDjFlag()!=null){
            if(baseVO.getDjFlag()){
                LambdaQueryWrapper<EduStudentEnrollPre> queryWrapper=new LambdaQueryWrapper<>();
                String finalIdcard = idcard;
                queryWrapper.eq(EduStudentEnrollPre::getYear, eduHelper.thisYear())
                        .and(wrapper -> {
                                    wrapper.eq(EduStudentEnrollPre::getFatherIdcard, finalIdcard)
                                            .or()
                                            .eq(EduStudentEnrollPre::getIdcard, finalIdcard)
                                            .or()
                                            .eq(EduStudentEnrollPre::getMotherIdcard, finalIdcard);
                                }).orderByAsc(EduStudentEnrollPre::getIdcard);
                if (eduStudentEnrollPreService.count(queryWrapper)>0){
                    checkFlag=true;
                }else{
                    checkFlag=false;
                }
            }
        }
        if(checkFlag) {
            //判断是否家长身份证
            List<PersonInformationAuthVO> authVOList = personInformationAuthService.getByIdcard(idcard);
            if (!CollectionUtils.isEmpty(authVOList)) {
                boolean flag = false;
                for (PersonInformationAuthVO authVO : authVOList) {
                    if (BoolEnum.TRUE.getType().equalsIgnoreCase(authVO.getPersonInformationStatus())) {
                        flag = true;
                        break;
                    }
                }
                return flag;
            } else {
                return false;
            }
        }else{
            return true;
        }
    }

    @Override
    @OpApi(funcCode = "personInformationAuth0002", title = "个人信息授权根据主键查询详情", funcType = FuncTypeEnum.query)
    public PersonInformationAuthVO getById(PersonInformationAuthKeyVO vo) {
        PersonInformationAuth entity = personInformationAuthService.getById(vo.getPersonInformationAuthId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        PersonInformationAuthVO result = Convert.convert(PersonInformationAuthVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "personInformationAuth0003", title = "个人信息授权保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(PersonInformationAuthVO vo) {
        if (StringUtils.isBlank(vo.getIdcard())){
            throw new AppException("授权人身份证不能为空");
        }
        if (StringUtils.isBlank(vo.getPersonInformationType())){
            throw new AppException("授权类型不能为空");
        }
        if (vo.getPersonInformationYear()==null){
            throw new AppException("年度不能为空");
        }
        //主键为空为新增校验
        QueryWrapper<PersonInformationAuth> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(PersonInformationAuth::getIdcard,vo.getIdcard())
                .eq(PersonInformationAuth::getPersonInformationType,vo.getPersonInformationType())
                .eq(PersonInformationAuth::getPersonInformationYear,vo.getPersonInformationYear())
                .ne(vo.getPersonInformationAuthId()!=null,PersonInformationAuth::getPersonInformationAuthId,vo.getPersonInformationAuthId());
        if (personInformationAuthService.count(queryWrapper)>0){
            throw new AppException("已存在授权类型");
        }
        //主键不为空为修改校验
    }

    @Override
    @OpApi(funcCode = "personInformationAuth0008", title = "授权信息保存", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void save(PersonInformationAuthSaveVO vo) {
        SessionInfo sessionInfo=SessionUtil.getSessionInfo();
        if (sessionInfo!=null){
            if (StringUtils.isBlank(vo.getIdcard())){
                vo.setIdcard(sessionInfo.getIdcard());
            }
            if (StringUtils.isBlank(vo.getUserId())){
                vo.setUserId(sessionInfo.getUserId());
            }
            if (vo.getPersonId()==null){
                vo.setPersonId(sessionInfo.getPersonId());
            }
        }
        if (StringUtils.isBlank(vo.getIdcard())){
            throw new AppException("授权人身份证不能为空");
        }
        Integer year=eduHelper.thisYear();
        List<PersonInformationAuth> saveList=new ArrayList<>();
        if (vo.getAllFlag()!=null&&vo.getAllFlag()){
            if (StringUtils.isBlank(vo.getPersonInformationStatus())){
                throw new AppException("授权状态不能为空");
            }
            List<PersonInformationAuthVO> authVOList=personInformationAuthService.getByIdcardNoCache(vo.getIdcard());
            if (CollectionUtils.isEmpty(authVOList)){
                throw new AppException("没有需要授权的数据");
            }
            for(PersonInformationAuthVO authVO:authVOList){
                PersonInformationAuth auth=Convert.convert(PersonInformationAuth.class,authVO);
                auth.setIdcard(vo.getIdcard());
                auth.setUserId(vo.getUserId());
                auth.setPersonId(vo.getPersonId());
                auth.setPersonInformationStatus(BoolEnum.TRUE.getType());
                auth.setSignatureFile(vo.getSignatureFile());
                auth.setPersonInformationYear(year);
                saveList.add(auth);
            }
        }else{
            if (!CollectionUtils.isEmpty(vo.getAuthVOList())){
                for(PersonInformationAuthVO authVO:vo.getAuthVOList()){
                    PersonInformationAuth auth=Convert.convert(PersonInformationAuth.class,authVO);
                    auth.setIdcard(vo.getIdcard());
                    auth.setUserId(vo.getUserId());
                    auth.setPersonId(vo.getPersonId());
                    if (StringUtils.isBlank(auth.getPersonInformationStatus())){
                        auth.setPersonInformationStatus(BoolEnum.FALSE.getType());
                    }
                    auth.setSignatureFile(vo.getSignatureFile());
                    auth.setPersonInformationYear(year);
                    saveList.add(auth);
                }
            }
        }
        if (!CollectionUtils.isEmpty(saveList)){
            personInformationAuthService.saveOrUpdateBatch(saveList);
        }
        personInformationAuthService.clearCache(vo.getIdcard());
    }

    @Override
    @OpApi(funcCode = "personInformationAuth0004", title = "个人信息授权新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "personInformationAuth0004",
            operationName = "个人信息授权新增",
            dataType = "personInformationAuthId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public PersonInformationAuthVO add(PersonInformationAuthVO vo) {
        SessionInfo sessionInfo=SessionUtil.getSessionInfo();
        if (sessionInfo!=null){
            if (StringUtils.isBlank(vo.getIdcard())){
                vo.setIdcard(sessionInfo.getIdcard());
            }
            if (StringUtils.isBlank(vo.getUserId())){
                vo.setUserId(sessionInfo.getUserId());
            }
            if (vo.getPersonId()==null){
                vo.setPersonId(sessionInfo.getPersonId());
            }
        }
        vo.setPersonInformationYear(eduHelper.thisYear());

        //保存前校验
        checkSave(vo);
        //保存数据
        PersonInformationAuth entity = Convert.convert(PersonInformationAuth.class, vo);
        personInformationAuthService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setPersonInformationAuthId(entity.getPersonInformationAuthId());
        personInformationAuthService.clearCache(vo.getIdcard());
        return vo;
    }

    @Override
    @OpApi(funcCode = "personInformationAuth0005", title = "个人信息授权修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "personInformationAuth0005",
            operationName = "个人信息授权修改",
            dataType = "personInformationAuthId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public PersonInformationAuthVO edit(PersonInformationAuthVO vo) {
        if (ObjectUtils.isEmpty(vo.getPersonInformationAuthId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        PersonInformationAuth oldEntity = personInformationAuthService.getById(vo.getPersonInformationAuthId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        //保存前校验
        checkSave(vo);
        //保存数据
        PersonInformationAuth entity = Convert.convert(PersonInformationAuth.class, vo);
        personInformationAuthService.updateById(entity);
        personInformationAuthService.clearCache(vo.getIdcard());
        return vo;
    }

    @Override
    @OpApi(funcCode = "personInformationAuth0006", title = "个人信息授权根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "personInformationAuth0006",
            operationName = "个人信息授权删除",
            dataType = "personInformationAuthId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(PersonInformationAuthKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getPersonInformationAuthId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        PersonInformationAuth entity = personInformationAuthService.getById(vo.getPersonInformationAuthId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        personInformationAuthService.removeById(vo.getPersonInformationAuthId());
        personInformationAuthService.clearCache(entity.getIdcard());
    }
}
